from masonite.controllers import Controller
from masonite.views import View
from masonite.request import Request
from masonite.response import Response
from app.traits.MyControllerTrait import MyControllerTrait
from app.traits.MyModelTrait import MyModelTrait
from app.models.AdminUserLoginLog import AdminUserLoginLog
from app.models.AdminUser import AdminUser
from masoniteorm.collection import Collection


class AdminUserLoginLogController(Controller):
    uri = "/admin/user-login-log"
    temp = "admin.user-login-log"

    def index(self, view: View):
        uri = self.uri + '/index'
        data = {
            'uri': self.uri,
            'menus': MyControllerTrait.get_menu_nav(uri),
            'title': MyControllerTrait.get_permission_title(uri)
        }
        return view.render(self.temp + ".index", data)

    def show(self, request: Request, response: Response):
        admin_user_account = request.input("admin_user_account")
        created_at = request.input("created_at")
        page = request.input("page", 1)
        limit = request.input("limit", 10)

        table = AdminUserLoginLog.get_table_name()
        where = ''
        order = 'id DESC'

        if len(admin_user_account) > 0:
            admin_users = AdminUser.where_like('account', "{0}%".format(admin_user_account)).get()
            if admin_users is not None:
                # 1,2,3
                ids = ''
                for admin_user in admin_users:
                    ids += str(admin_user['id']) + ','
                ids = ids.strip(',')
                if len(ids) > 0:
                    where += " AND admin_user_id IN ({0})".format(ids)
                else:
                    where += " AND admin_user_id IN (0)"

        if len(created_at) > 2:
            where += " AND created_at >= '{0}'".format(created_at)

        total, admin_user_login_logs = MyModelTrait.search_for_show(table, where, "*", page, limit, order)
        admin_users = AdminUser.get_account()
        if admin_user_login_logs is not None:
            for index, admin_user_login_log in enumerate(admin_user_login_logs):
                account = "-"
                if admin_user_login_log['admin_user_id'] in admin_users:
                    account = admin_users[admin_user_login_log['admin_user_id']]
                admin_user_login_logs[index]['admin_user_account'] = account
                admin_user_login_logs[index]['created_at'] = MyControllerTrait.time_format_conversion(admin_user_login_log['created_at'])

        data = {
            'code': 0,
            'message': 'success',
            'total': total,
            'data': admin_user_login_logs
        }

        return response.json(data)
